package com.health.mapp.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse.Credentials;
import com.health.commons.PropertiesService;
import com.health.db.model.TrainingBase;
import com.health.db.model.TrainingEnter;
import com.health.db.model.TrainingEnterExample;
import com.health.db.service.user.ITrainingBaseService;
import com.health.db.service.user.ITrainingEnterService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.TrainingEnterReq;
import com.health.mapp.bean.TrainingEnterResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 * 报名接口
 * 库存未做
 * @author YC
 *
 */
public class TrainingEnterImpl  implements ActionInterface{

	private static Logger logger = Logger.getLogger(TrainingEnterImpl.class);
	@Autowired
	ITrainingEnterService trainingEnterService;
	
	@Autowired
	ITrainingBaseService trainingBaseService;
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		TrainingEnterReq req = (TrainingEnterReq) reqBean;
		TrainingEnterResp _resp = new TrainingEnterResp();
		
		if (StringUtils.isEmpty( req.getTnId())||StringUtils.isEmpty(req.getContactPhone())) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}else{
			TrainingEnter record = new TrainingEnter();
			record = this.packageTrainingEnter(req);
			
			//查询课程名称
			TrainingBase trainingBase = trainingBaseService.selectByPrimaryKey(record.getTnId());
			//查询课程是否存在
			if (null==trainingBase) {
				_resp.setErrorCode(-8888);
				_resp.setErrorMsg("课程选择错误");
				return _resp;	
			}
			
			String repeatEnter = PropertiesService.getString("training.repeatEnter").trim();
			
			//重复提交
			if (repeatEnter.equals("1")) {
				TrainingEnterExample example = new TrainingEnterExample(); 
				example.setTnId(record.getTnId());
				example.setContactName(record.getContactPhone().trim());
				
				List<TrainingEnter> enterList =trainingEnterService.selectByExample(example);
				
				if (enterList.size()>0) {
					_resp.setErrorCode(-8888);
					_resp.setErrorMsg("课程已报名,请勿重复报名!");
					return _resp;	
				}
			}
			
			//icon不为空
			if (StringUtils.isNotBlank(record.getIconPhotoUrl())) {
				String copy1 = "trainingEnterIcon/标题/"+trainingBase.getTnName()+"-"+trainingBase.getTnSubName()+"/"+record.getContactPhone()+"_"+record.getContactName()+getExtension(record.getIconPhotoUrl());
				String copy2 = "trainingEnterIcon/ID/"+trainingBase.getId()+"/"+record.getIconPhotoUrl().replace("trainingEnterIcon/", "");
				
				backUpIcon(record.getIconPhotoUrl(), copy1,copy2);
				record.setIconPhotoUrl(copy2);
				record.setIconPhotoUrlCopy(copy1);
			}
			
			record.setTnName(trainingBase.getTnName());
			int ecexutNum=trainingEnterService.insert(record);
		}
	
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
		
		return _resp;
	}
	
	
    public static String getExtension(String fileName) throws Exception {

        if (null != fileName) {
            int pos = fileName.lastIndexOf(".");
            if (pos > 0) {
                return fileName.substring(pos);
            }

        }
        return "";

    }

	/**
	 * 包装入参
	 * @param req
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private TrainingEnter packageTrainingEnter(TrainingEnterReq req) throws IllegalAccessException, InvocationTargetException{
		
		TrainingEnter record = new TrainingEnter();
		
		BeanUtils.copyProperties(req, record);
		record.setTnId(Long.valueOf(req.getTnId()));
		record.setStatue(Constant.LIQIAO_ENTER_STATUS_1);
		//支付未加
		record.setPayFlag(Constant.LIQIAO_PAY_FLAG_1);
		record.setPayType(Constant.LIQIAO_PAY_TYPE_1);
		record.setIsDelete(Constant.LIQIAO_IS_DELETE_1);
		record.setSex(Integer.valueOf(req.getSex()));
		record.setIsPassedFlag(Constant.LIQIAO_IS_PASSED_FLAG_1);
		record.setInvoiceFlag(StringUtils.isEmpty(req.getInvoiceFlag())?Constant.LIQIAO_INVOICE_FLAG_1:Integer.valueOf(req.getInvoiceFlag()));
		record.setIsHotelFlag(StringUtils.isEmpty(req.getIsHotelFlag())?Constant.LIQIAO_IS_HOTEL_FLAG_1:Integer.valueOf(req.getIsHotelFlag()));
		return record;
		
	}
	
	
	public ITrainingEnterService getTrainingEnterService() {
		return trainingEnterService;
	}

	public void setTrainingEnterService(ITrainingEnterService trainingEnterService) {
		this.trainingEnterService = trainingEnterService;
	}
	
	/**
	 * 拷贝oss文件 
	 * @param name
	 * @param backUpName
	 */
    public static void backUpIcon(String name,String backUpName,String backUpName2) {

    	logger.fatal("uploadByOss start....................");
        String accessKeyId = PropertiesService.getString("oss.accessKeyId").trim();
        String accessKeySecret = PropertiesService.getString("oss.accessKeySecret").trim();
        String roleArn = PropertiesService.getString("oss.roleReadWrite").trim();
        String roleSessionName = PropertiesService.getString("oss.roleSessionName").trim();
        String endpoint = PropertiesService.getString("oss.endpoint").trim();
        String bucketName = PropertiesService.getString("oss.bucketName").trim();
        
        String policy = "{\n" +
                "	\"Version\": \"1\",\n" +
                "	\"Statement\": [\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "		    \"Action\": [\n" +
                "		    	\"oss:ListObjects\",\n" +
                "		    	\"oss:GetObject\"\n" +
                "		    ],\n" +
                "		    \"Resource\": [\n" +
                "		    	\"acs:oss:*:*:"+bucketName+"\",\n" +
                "		   		\"acs:oss:*:*:"+bucketName+"/*\"\n" +
                "		    ]\n" +
                "		},\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "			\"Action\": [\n" +
                "				\"oss:AbortMultipartUpload\",\n" +
                "				\"oss:PutObject\",\n" +
                "				\"oss:DeleteObject\"\n" +
                "			],\n" +
                "			\"Resource\": [\n" +
                "		    	\"acs:oss:*:*:"+bucketName+"\",\n" +
                "		   		\"acs:oss:*:*:"+bucketName+"/*\"\n" +                
                "			]\n" +
                "		}\n" +
                "   ]\n" +
                "}";

        ProtocolType protocolType = ProtocolType.HTTPS;
        Credentials credentials = null;
        try {
            final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                    roleArn, roleSessionName, policy, protocolType);

            if (null != response) {
                credentials = response.getCredentials();


                if (null != credentials) {
                    String accessKeyIdByToken = credentials.getAccessKeyId();
                    String accessKeySecretByToken = credentials.getAccessKeySecret();
                    String securityByToken = credentials.getSecurityToken();
                    OSSClient client = new OSSClient(endpoint, accessKeyIdByToken, accessKeySecretByToken, securityByToken);
                    logger.fatal("key:" + name);
                    
                    if(client.doesObjectExist(bucketName, name)){
                    	logger.info("object is exit");
                        client.copyObject(bucketName, name, bucketName, backUpName);
                        client.copyObject(bucketName, name, bucketName, backUpName2);
                        client.deleteObject(bucketName, name);
                    }else{
                    	
                    	logger.info("object is not exit");
                    }
              
                   
                } else {
                	logger.fatal("credentials is " + credentials);
                	logger.info("credentials is " + credentials);
                }
            } else {

            	logger.fatal("response is " + response);
            	logger.info("response is " + response);

            }
        } catch (ClientException e) {
        	logger.info("ERROR");
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
        	logger.info("ERROR");
            e.printStackTrace();

        }

        logger.fatal("uploadByOss end....................");

    }

    static AssumeRoleResponse assumeRole(String accessKeyId,
                                         String accessKeySecret, String roleArn, String roleSessionName,
                                         String policy, ProtocolType protocolType) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile(
                PropertiesService.getString("oss.region").trim(), accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setActionName("AssumeRole");
        request.setVersion(PropertiesService.getString("oss.stsApiVersion").trim());
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);
        AssumeRoleResponse response = client.getAcsResponse(request);
        return response;

    }


}
